package com.aia.ilp.web.json;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.util.StringUtils;

import com.aia.ilp.domain.Cust;
import com.aia.ilp.service.MainService;
import com.cfh.ahead.Constant;
import com.cfh.util.Tools;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class CustomerResetPasswordJson extends ActionSupport implements ModelDriven<Cust>, SessionAware {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CustomerResetPasswordJson.class);

	private Cust custToReg = new Cust();
	private Map session;
	private String REG_IMAGE_CODE;
	private MainService mainService;
	public void validate() {
		try {
			
			{// 登录？
				Cust loginCust = (Cust) getSession().get("customer");
				if (loginCust != null) {
					addActionError("您已经登录了，请先注销该活动用户");
					return;
				}
			}
			
			{// 较验验证码
				String imgCode = (String) session.get(Constant.CAPTCHA_SESSION_HOLDER);
				if (!StringUtils.hasText(imgCode)) {
					addFieldError("REG_IMAGE_CODE", "请再次获取图片验证码");
					return;
				}

				if (!StringUtils.hasText(REG_IMAGE_CODE)) {
					addFieldError("REG_IMAGE_CODE", "请输入图片验证码");
					return;
				}
				if (!REG_IMAGE_CODE.toLowerCase().equals(imgCode)) {
					addFieldError("REG_IMAGE_CODE", "验证码输入错误");
					return;
				}
			}

		} catch (Exception e) {
			addFieldError("SERVER_ERROR", "未知的较验错误");
			logger.error("validate()", e); //$NON-NLS-1$
			// throw new RuntimeException(e);
		}

	}

	/***
	 * nouse
	 */
	public String execute() {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}
		
		unescapeCust(getCustToReg());

		mainService.updateCustomerResetPassword(this);

		if(Tools.isSuccess(this)){
			session.put(Constant.CAPTCHA_SESSION_HOLDER, "");
		}
		String returnString = Tools.smartReturn(this);
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - end"); //$NON-NLS-1$
		}
		return returnString;
	}

	private void unescapeCust(Cust c) {
		c.setCUST_SECURITY_A(Tools.unescapeTwice(c.getCUST_SECURITY_A()));
	}

	public Cust getModel() {
		return custToReg;
	}

	public void setCustToReg(Cust custToReg) {
		this.custToReg = custToReg;
	}

	public Cust getCustToReg() {
		return custToReg;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public Map getSession() {
		return session;
	}


	public void setREG_IMAGE_CODE(String rEG_IMAGE_CODE) {
		REG_IMAGE_CODE = rEG_IMAGE_CODE;
	}

	public String getREG_IMAGE_CODE() {
		return REG_IMAGE_CODE;
	}

	public void setMainService(MainService mainService) {
		this.mainService = mainService;
	}

	public MainService getMainService() {
		return mainService;
	}

}
